package cn.chrilwe.zk.starter.config;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooKeeper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * @author chrilwe
 * 2020-7-26
 */
@Configuration
@Slf4j
@ConditionalOnBean(ZkAutoMarkConfiguration.Mark.class)
public class ZkAutoConfiguration {
	
	@Autowired
	protected ZkConfig zkConfig;

	@Bean
	public ZooKeeper zookeeper() {
		System.out.println("hello");
		if(zkConfig == null) {
			throw new RuntimeException("zkConfig can not be null");
		}
		CountDownLatch cdl = new CountDownLatch(1);
		try {
			ZooKeeper client = new ZooKeeper(zkConfig.connectString, zkConfig.getSessionTimeout(), new Watcher() {
				
				@Override
				public void process(WatchedEvent event) {
					if(event.getState().equals(KeeperState.SyncConnected)) {
						cdl.countDown();
					}
				}
			});
			
			try {
				cdl.await();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			log.info("zookeeper client connect to server success");
			
			createApplicationNamePath(zkConfig.getApplicationName(), zkConfig.getServerHostAndPort());
			createLockPath("/lock", client);
			
			return client;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	protected boolean createLockPath(String lockPath, ZooKeeper client) {
		try {
			String create = client.create(lockPath, "".getBytes(), null, CreateMode.PERSISTENT);
			if(StringUtils.isEmpty(create)) {
				return false;
			}
			return true;
		} catch (KeeperException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}
	
	protected boolean createApplicationNamePath(String applicationName, String serverHostAndPort) {
		
		return false;
	}
}
